home *** CD-ROM | disk | FTP | other *** search
/ Programming a Multiplayer FPS in DirectX / Programming a Multiplayer FPS in DirectX (Companion CD).iso / Source / Chapter 9 / Engine / Engine.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-03-29  |  15.0 KB  |  459 lines

  1. //-----------------------------------------------------------------------------
  2. // Engine.h implementation.
  3. // Refer to the Engine.h interface for more details.
  4. //
  5. // Programming a Multiplayer First Person Shooter in DirectX
  6. // Copyright (c) 2004 Vaughan Young
  7. //-----------------------------------------------------------------------------
  8. #include "Engine.h"
  9.  
  10. //-----------------------------------------------------------------------------
  11. // Globals
  12. //-----------------------------------------------------------------------------
  13. Engine *g_engine = NULL;
  14.  
  15. //-----------------------------------------------------------------------------
  16. // Handles Windows messages.
  17. //-----------------------------------------------------------------------------
  18. LRESULT CALLBACK WindowProc( HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam )
  19. {
  20.     switch( msg )
  21.     {
  22.         case WM_ACTIVATEAPP:
  23.             g_engine->SetDeactiveFlag( !wparam );
  24.             return 0;
  25.  
  26.         case WM_DESTROY:
  27.             PostQuitMessage( 0 );
  28.             return 0;
  29.  
  30.         default:
  31.             return DefWindowProc( wnd, msg, wparam, lparam );
  32.     }
  33. }
  34.  
  35. //-----------------------------------------------------------------------------
  36. // The engine class constructor.
  37. //-----------------------------------------------------------------------------
  38. Engine::Engine( EngineSetup *setup )
  39. {
  40.     // Indicate that the engine is not yet loaded.
  41.     m_loaded = false;
  42.  
  43.     // If no setup structure was passed in, then create a default one.
  44.     // Otehrwise, make a copy of the passed in structure.
  45.     m_setup = new EngineSetup;
  46.     if( setup != NULL )
  47.         memcpy( m_setup, setup, sizeof( EngineSetup ) );
  48.  
  49.     // Store a pointer to the engine in a global variable for easy access.
  50.     g_engine = this;
  51.  
  52.     // Prepare and register the window class.
  53.     WNDCLASSEX wcex;
  54.     wcex.cbSize        = sizeof( WNDCLASSEX );
  55.     wcex.style         = CS_CLASSDC;
  56.     wcex.lpfnWndProc   = WindowProc;
  57.     wcex.cbClsExtra    = 0;
  58.     wcex.cbWndExtra    = 0;
  59.     wcex.hInstance     = m_setup->instance;
  60.     wcex.hIcon         = LoadIcon( NULL, IDI_APPLICATION );
  61.     wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
  62.     wcex.hbrBackground = NULL;
  63.     wcex.lpszMenuName  = NULL;
  64.     wcex.lpszClassName = "WindowClass";
  65.     wcex.hIconSm       = LoadIcon( NULL, IDI_APPLICATION );
  66.     RegisterClassEx( &wcex );
  67.  
  68.     // Initialise the COM using multithreaded concurrency.
  69.     CoInitializeEx( NULL, COINIT_MULTITHREADED );
  70.  
  71.     // Create the Direct3D interface.
  72.     IDirect3D9 *d3d = Direct3DCreate9( D3D_SDK_VERSION );
  73.  
  74.     // Enumerate Direct3D device configurations on the default adapter.
  75.     g_deviceEnumeration = new DeviceEnumeration;
  76.     if( g_deviceEnumeration->Enumerate( d3d ) != IDOK )
  77.     {
  78.         SAFE_RELEASE( d3d );
  79.         return;
  80.     }
  81.  
  82.     // Create the window and retrieve a handle to it.
  83.     m_window = CreateWindow( "WindowClass", m_setup->name, g_deviceEnumeration->IsWindowed() ? WS_OVERLAPPED : WS_POPUP, 0, 0, 800, 600, NULL, NULL, m_setup->instance, NULL );
  84.  
  85.     // Prepare the device presentation parameters.
  86.     D3DPRESENT_PARAMETERS d3dpp;
  87.     ZeroMemory( &d3dpp, sizeof( D3DPRESENT_PARAMETERS ) );
  88.     d3dpp.BackBufferWidth = g_deviceEnumeration->GetSelectedDisplayMode()->Width;
  89.     d3dpp.BackBufferHeight = g_deviceEnumeration->GetSelectedDisplayMode()->Height;
  90.     d3dpp.BackBufferFormat = g_deviceEnumeration->GetSelectedDisplayMode()->Format;
  91.     d3dpp.BackBufferCount = m_setup->totalBackBuffers;
  92.     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  93.     d3dpp.hDeviceWindow = m_window;
  94.     d3dpp.Windowed = g_deviceEnumeration->IsWindowed();
  95.     d3dpp.EnableAutoDepthStencil = true;
  96.     d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  97.     d3dpp.FullScreen_RefreshRateInHz = g_deviceEnumeration->GetSelectedDisplayMode()->RefreshRate;
  98.     if( g_deviceEnumeration->IsVSynced() == true )
  99.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  100.     else
  101.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  102.  
  103.     // Destroy the device enumeration object.
  104.     SAFE_DELETE( g_deviceEnumeration );
  105.  
  106.     // Create the Direct3D device.
  107.     if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_window, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &m_device ) ) )
  108.         return;
  109.  
  110.     // Release the Direct3D interface as it is no longer needed.
  111.     SAFE_RELEASE( d3d );
  112.  
  113.     // Switch lighting off by default.
  114.     m_device->SetRenderState( D3DRS_LIGHTING, false );
  115.  
  116.     // Set the texture filters to use anisotropic texture filtering.
  117.     m_device->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC );
  118.     m_device->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC );
  119.     m_device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );
  120.  
  121.     // Set the projection matrix.
  122.     D3DXMATRIX projMatrix;
  123.     D3DXMatrixPerspectiveFovLH( &projMatrix, D3DX_PI / 4, (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight, 0.1f / m_setup->scale, 1000.0f / m_setup->scale );
  124.     m_device->SetTransform( D3DTS_PROJECTION, &projMatrix );
  125.  
  126.     // Store the display mode details.
  127.     m_displayMode.Width = d3dpp.BackBufferWidth;
  128.     m_displayMode.Height = d3dpp.BackBufferHeight;
  129.     m_displayMode.RefreshRate = d3dpp.FullScreen_RefreshRateInHz;
  130.     m_displayMode.Format = d3dpp.BackBufferFormat;
  131.  
  132.     // The swap chain always starts on the first back buffer.
  133.     m_currentBackBuffer = 0;
  134.  
  135.     // Create the sprite interface.
  136.     D3DXCreateSprite( m_device, &m_sprite );
  137.  
  138.     // Create the linked lists of states.
  139.     m_states = new LinkedList< State >;
  140.     m_currentState = NULL;
  141.  
  142.     // Create the resource managers.
  143.     m_scriptManager = new ResourceManager< Script >;
  144.     m_materialManager = new ResourceManager< Material >( m_setup->CreateMaterialResource );
  145.     m_meshManager = new ResourceManager< Mesh >;
  146.  
  147.     // Create the input object.
  148.     m_input = new Input( m_window );
  149.  
  150.     // Create the network object.
  151.     m_network = new Network( m_setup->guid, m_setup->HandleNetworkMessage );
  152.  
  153.     // Create the sound system.
  154.     m_soundSystem = new SoundSystem( m_setup->scale );
  155.  
  156.     // Seed the random number generator with the current time.
  157.     srand( timeGetTime() );
  158.  
  159.     // Allow the application to perform any state setup now.
  160.     if( m_setup->StateSetup != NULL )
  161.         m_setup->StateSetup();
  162.  
  163.     // The engine is fully loaded and ready to go.
  164.     m_loaded = true;
  165. }
  166.  
  167. //-----------------------------------------------------------------------------
  168. // The engine class destructor.
  169. //-----------------------------------------------------------------------------
  170. Engine::~Engine()
  171. {
  172.     // Ensure the engine is loaded.
  173.     if( m_loaded == true )
  174.     {
  175.         // Destroy the states linked lists.
  176.         if( m_currentState != NULL )
  177.             m_currentState->Close();
  178.         SAFE_DELETE( m_states );
  179.  
  180.         // Destroy everything.
  181.         SAFE_DELETE( m_soundSystem );
  182.         SAFE_DELETE( m_network );
  183.         SAFE_DELETE( m_input );
  184.         SAFE_DELETE( m_meshManager );
  185.         SAFE_DELETE( m_materialManager );
  186.         SAFE_DELETE( m_scriptManager );
  187.  
  188.         // Release the sprite interface.
  189.         SAFE_RELEASE( m_sprite );
  190.  
  191.         // Release the device.
  192.         SAFE_RELEASE( m_device );
  193.     }
  194.  
  195.     // Uninitialise the COM.
  196.     CoUninitialize();
  197.  
  198.     // Unregister the window class.
  199.     UnregisterClass( "WindowClass", m_setup->instance );
  200.  
  201.     // Destroy the engine setup structure.
  202.     SAFE_DELETE( m_setup );
  203. }
  204.  
  205. //-----------------------------------------------------------------------------
  206. // Enters the engine into the main processing loop.
  207. //-----------------------------------------------------------------------------
  208. void Engine::Run()
  209. {
  210.     // Ensure the engine is loaded.
  211.     if( m_loaded == true )
  212.     {
  213.         // Show the window.
  214.         ShowWindow( m_window, SW_NORMAL );
  215.  
  216.         // Used to retrieve details about the viewer from the application.
  217.         ViewerSetup viewer;
  218.  
  219.         // Enter the message loop.
  220.         MSG msg;
  221.         ZeroMemory( &msg, sizeof( MSG ) );
  222.         while( msg.message != WM_QUIT )
  223.         {
  224.             if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
  225.             {
  226.                 TranslateMessage( &msg );
  227.                 DispatchMessage( &msg );
  228.             }
  229.             else if( !m_deactive )
  230.             {
  231.                 // Calculate the elapsed time.
  232.                 unsigned long currentTime = timeGetTime();
  233.                 static unsigned long lastTime = currentTime;
  234.                 float elapsed = ( currentTime - lastTime ) / 1000.0f;
  235.                 lastTime = currentTime;
  236.  
  237.                 // Update the network object, processing any pending messages.
  238.                 m_network->Update();
  239.  
  240.                 // Update the input object, reading the keyboard and mouse.
  241.                 m_input->Update();
  242.  
  243.                 // Check if the user wants to make a forced exit.
  244.                 if( m_input->GetKeyPress( DIK_F1 ) )
  245.                     PostQuitMessage( 0 );
  246.  
  247.                 // Request the viewer from the current state, if there is one.
  248.                 if( m_currentState != NULL )
  249.                     m_currentState->RequestViewer( &viewer );
  250.  
  251.                 // Ensure the viewer is valid.
  252.                 if( viewer.viewer != NULL )
  253.                 {
  254.                     // Set the view transformation.
  255.                     m_device->SetTransform( D3DTS_VIEW, viewer.viewer->GetViewMatrix() );
  256.  
  257.                     // Update the 3D sound listener.
  258.                     m_soundSystem->UpdateListener( viewer.viewer->GetForwardVector(), viewer.viewer->GetTranslation(), viewer.viewer->GetVelocity() );
  259.                 }
  260.  
  261.                 // Update the current state (if there is one), taking state
  262.                 // changes into account.
  263.                 m_stateChanged = false;
  264.                 if( m_currentState != NULL )
  265.                     m_currentState->Update( elapsed );
  266.                 if( m_stateChanged == true )
  267.                     continue;
  268.  
  269.                 // Begin the scene.
  270.                 m_device->Clear( 0, NULL, viewer.viewClearFlags, 0, 1.0f, 0 );
  271.                 if( SUCCEEDED( m_device->BeginScene() ) )
  272.                 {
  273.                     // Render the current state, if there is one.
  274.                     if( m_currentState != NULL )
  275.                         m_currentState->Render();
  276.  
  277.                     // End the scene and present it.
  278.                     m_device->EndScene();
  279.                     m_device->Present( NULL, NULL, NULL, NULL );
  280.  
  281.                     // Keep track of the index of the current back buffer.
  282.                     if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  283.                         m_currentBackBuffer = 0;
  284.                 }
  285.             }
  286.         }
  287.     }
  288.  
  289.     // Destroy the engine.
  290.     SAFE_DELETE( g_engine );
  291. }
  292.  
  293. //-----------------------------------------------------------------------------
  294. // Returns the window handle.
  295. //-----------------------------------------------------------------------------
  296. HWND Engine::GetWindow()
  297. {
  298.     return m_window;
  299. }
  300.  
  301. //-----------------------------------------------------------------------------
  302. // Sets the deactive flag.
  303. //-----------------------------------------------------------------------------
  304. void Engine::SetDeactiveFlag( bool deactive )
  305. {
  306.     m_deactive = deactive;
  307. }
  308.  
  309. //-----------------------------------------------------------------------------
  310. // Returns the scale that the engine is currently running in.
  311. //-----------------------------------------------------------------------------
  312. float Engine::GetScale()
  313. {
  314.     return m_setup->scale;
  315. }
  316.  
  317. //-----------------------------------------------------------------------------
  318. // Returns a pointer to the Direct3D device.
  319. //-----------------------------------------------------------------------------
  320. IDirect3DDevice9 *Engine::GetDevice()
  321. {
  322.     return m_device;
  323. }
  324.  
  325. //-----------------------------------------------------------------------------
  326. // Returns a pointer to the display mode of the current Direct3D device.
  327. //-----------------------------------------------------------------------------
  328. D3DDISPLAYMODE *Engine::GetDisplayMode()
  329. {
  330.     return &m_displayMode;
  331. }
  332.  
  333. //-----------------------------------------------------------------------------
  334. // Returns a pointer to the sprite interface.
  335. //-----------------------------------------------------------------------------
  336. ID3DXSprite *Engine::GetSprite()
  337. {
  338.     return m_sprite;
  339. }
  340.  
  341. //-----------------------------------------------------------------------------
  342. // Adds a state to the engine.
  343. //-----------------------------------------------------------------------------
  344. void Engine::AddState( State *state, bool change )
  345. {
  346.     m_states->Add( state );
  347.  
  348.     if( change == false )
  349.         return;
  350.  
  351.     if( m_currentState != NULL )
  352.         m_currentState->Close();
  353.  
  354.     m_currentState = m_states->GetLast();
  355.     m_currentState->Load();
  356. }
  357.  
  358. //-----------------------------------------------------------------------------
  359. // Removes a state from the engine
  360. //-----------------------------------------------------------------------------
  361. void Engine::RemoveState( State *state )
  362. {
  363.     m_states->Remove( &state );
  364. }
  365.  
  366. //-----------------------------------------------------------------------------
  367. // Changes processing to the state with the specified ID.
  368. //-----------------------------------------------------------------------------
  369. void Engine::ChangeState( unsigned long id )
  370. {
  371.     // Iterate through the list of states and find the new state to change to.
  372.     m_states->Iterate( true );
  373.     while( m_states->Iterate() != NULL )
  374.     {
  375.         if( m_states->GetCurrent()->GetID() == id )
  376.         {
  377.             // Close the old state.
  378.             if( m_currentState != NULL )
  379.                 m_currentState->Close();
  380.  
  381.             // Let the sound system perform garbage collection.
  382.             m_soundSystem->GarbageCollection();
  383.  
  384.             // Set the new current state and load it.
  385.             m_currentState = m_states->GetCurrent();
  386.             m_currentState->Load();
  387.  
  388.             // Swap the back buffers until the first one is in the front.
  389.             while( m_currentBackBuffer != 0 )
  390.             {
  391.                 m_device->Present( NULL, NULL, NULL, NULL );
  392.  
  393.                 if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  394.                     m_currentBackBuffer = 0;
  395.             }
  396.  
  397.             // Indicate that the state has changed.
  398.             m_stateChanged = true;
  399.  
  400.             break;
  401.         }
  402.     }
  403. }
  404.  
  405. //-----------------------------------------------------------------------------
  406. // Returns a pointer to the current state.
  407. //-----------------------------------------------------------------------------
  408. State *Engine::GetCurrentState()
  409. {
  410.     return m_currentState;
  411. }
  412.  
  413. //-----------------------------------------------------------------------------
  414. // Returns a pointer to the script manager.
  415. //-----------------------------------------------------------------------------
  416. ResourceManager< Script > *Engine::GetScriptManager()
  417. {
  418.     return m_scriptManager;
  419. }
  420.  
  421. //-----------------------------------------------------------------------------
  422. // Returns a pointer to the material manager.
  423. //-----------------------------------------------------------------------------
  424. ResourceManager< Material > *Engine::GetMaterialManager()
  425. {
  426.     return m_materialManager;
  427. }
  428.  
  429. //-----------------------------------------------------------------------------
  430. // Returns a pointer to the mesh manager.
  431. //-----------------------------------------------------------------------------
  432. ResourceManager< Mesh > *Engine::GetMeshManager()
  433. {
  434.     return m_meshManager;
  435. }
  436.  
  437. //-----------------------------------------------------------------------------
  438. // Returns a pointer to the input object.
  439. //-----------------------------------------------------------------------------
  440. Input *Engine::GetInput()
  441. {
  442.     return m_input;
  443. }
  444.  
  445. //-----------------------------------------------------------------------------
  446. // Returns a pointer to the network object.
  447. //-----------------------------------------------------------------------------
  448. Network *Engine::GetNetwork()
  449. {
  450.     return m_network;
  451. }
  452.  
  453. //-----------------------------------------------------------------------------
  454. // Returns a pointer to the sound system.
  455. //-----------------------------------------------------------------------------
  456. SoundSystem *Engine::GetSoundSystem()
  457. {
  458.     return m_soundSystem;
  459. }